<template>
  <Header :onCancel="onCancel" ref="header" title="搜索" />
  <div class="results-panel" v-if="results.length > 0">
    <SearchItem v-for="(item, index) in results" :movie="item" :key="index" />
  </div>
</template>
<script>
import { defineComponent } from "vue";
import Header from "@/components/Header";
import SearchItem from "@/components/SearchItem";
import { ref, onMounted, watch } from "vue";
import { searchMovies } from "@/api/movie";
import axios from "axios";
import { dealData } from "@/utils/filter";
export default defineComponent({
  components: {
    SearchItem,
    Header,
  },
  setup() {
    const header = ref(null);
    const results = ref([]);
    onMounted(() => {
      watch(
        () => header.value.keyword,
        (c, p, onInvalidate) => {
          const source = axios.CancelToken.source();
          searchMovies(
            {
              q: c,
            },
            source.token
          ).then(
            function (res) {
              results.value = dealData(res);
              console.log(results.value);
            },
            function (err) {
              console.log(err);
            }
          );
          onInvalidate(() => {
            source.cancel("请求已取消");
          });
        },
        {
          immediate: true,
          deep: true,
        }
      );
    });
    const onCancel = () => {
      source.cancel("点击了清除");
      //
    };
    return {
      header,
      results,
      onCancel,
    };
  },
});
</script>
<style>
.results-panel {
  padding-top: 15px;
}
</style>